package com.example.ywj.toutiao.fragments;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.bean.SVideo;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.MySVideoBaseAdapter;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Fragment3 extends Fragment {
    private static final String TAG = "Fragment3";
    public View view;
    //是否可见
    public boolean isVisible = false;
    //是否初始化完成
    public boolean isInit = false;
    //是否已经加载过
    public boolean isLoadOver = false;
    public String baseUrl = Constant.BASEURL;
    public String title;
    public PullToRefreshGridView pullToRefreshGridView;
    public Integer page = 0;
    public List<SVideo> list = new ArrayList<>();
    public MySVideoBaseAdapter mySVideoBaseAdapter;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null){
            view = inflater.inflate(R.layout.fragment3_layout, null);
            isInit = true;
            initView();
        }
        return view;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisible = isVisibleToUser;
        initView();
    }
    public void initView(){
        if (isInit && !isLoadOver && isVisible) {
            isLoadOver = true;
            title = getArguments().getString("title");
            //TextView tv = view.findViewById(R.id.text);
            //tv.setText(title);
            pullToRefreshGridView = view.findViewById(R.id.pull_refresh_list_fragment3);
            pullToRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
            ILoadingLayout down =pullToRefreshGridView.getLoadingLayoutProxy(true,false);//设置下拉文字
            ILoadingLayout up= pullToRefreshGridView.getLoadingLayoutProxy(false,true);
            down.setPullLabel("下拉刷新");// 刚下拉时，显示的提示
            down.setRefreshingLabel("拼命刷新中");// 刷新时
            down.setReleaseLabel("放开刷新");// 下来达到一定距离时，显示的提示
            down.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh));
            up.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh));
            up.setPullLabel("加载更多");
            up.setRefreshingLabel("拼命加载中");
            up.setReleaseLabel("放开加载");
            //pullToRefreshListView.setOnItemClickListener(Fragment3.this);
            getData(title);
        }
    }
    public void getData(String type){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getSVideo(type,page);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                    //Log.i(TAG, "onResponse: "+json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list = gson.fromJson(data,new TypeToken<ArrayList<SVideo>>(){}.getType());
                    mySVideoBaseAdapter = new MySVideoBaseAdapter(list);
                    pullToRefreshGridView.setAdapter(mySVideoBaseAdapter);
                    pullToRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
                        @Override
                        public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                            Retrofit retrofit = new Retrofit.Builder()
                                    .addConverterFactory(GsonConverterFactory.create())
                                    .baseUrl(baseUrl)
                                    .build();
                            ResponseApi responseApi = retrofit.create(ResponseApi.class);
                            Call<ResponseBody> call = responseApi.getSVideo(title,++page);
                            call.enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    String json = null;
                                    try {
                                        json = response.body().string();
                                        //Log.i(TAG, "onResponse: "+json);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    JsonObject obj = (JsonObject)new JsonParser().parse(json);
                                    Integer code = obj.get("statusCode").getAsInt();
                                    if(code == 200 &&obj.has("data")){
                                        JsonArray data = obj.getAsJsonArray("data");
                                        Gson gson = new Gson();
                                        List<SVideo> newList = gson.fromJson(data,new TypeToken<ArrayList<SVideo>>(){}.getType());
                                        list.clear();
                                        list.addAll(newList);
                                        mySVideoBaseAdapter.notifyDataSetChanged();
                                        pullToRefreshGridView.onRefreshComplete();
                                        if(newList.size()!=10){
                                            page = -1;
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {

                                }
                            });
                        }

                        @Override
                        public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                            Retrofit retrofit = new Retrofit.Builder()
                                    .addConverterFactory(GsonConverterFactory.create())
                                    .baseUrl(baseUrl)
                                    .build();
                            ResponseApi responseApi = retrofit.create(ResponseApi.class);
                            Call<ResponseBody> call = responseApi.getSVideo(title,++page);
                            call.enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    String json = null;
                                    try {
                                        json = response.body().string();
                                        Log.i(TAG, "onResponse: "+json);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    JsonObject obj = (JsonObject)new JsonParser().parse(json);
                                    Integer code = obj.get("statusCode").getAsInt();
                                    if(code == 200 && obj.has("data")){
                                        JsonArray objArr = obj.getAsJsonArray("data");
                                       Gson gson = new Gson();
                                       List<SVideo> newList = gson.fromJson(objArr,new TypeToken<ArrayList<SVideo>>(){}.getType());
                                       list.addAll(newList);
                                       mySVideoBaseAdapter.notifyDataSetChanged();
                                       pullToRefreshGridView.onRefreshComplete();
                                       if(newList.size()!=10){
                                            page = -1;
                                            }
                                        }

                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {

                                }
                            });
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure:出错了");
            }
        });
    }
}
